package com.glamour.hlcity.common.util;

import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import com.glamour.hlcity.common.exception.BizException;

/**
 * 替换填充数据替换"$xxxx"为特定的输入值
 * 
 * @author zhaoxing.liuzx
 */
public class VelocityUtil {

	private static VelocityUtil util = new VelocityUtil();

	private VelocityUtil() {
		try {
			Velocity.init();
		} catch (Exception e) {
			throw new BizException("failed to init VelocityUtil", e);
		}
	}

	public static VelocityUtil getUtil() {
		return util;
	}

	/**
	 * Map<String, String> map = new HashMap<String, String>();
	 * map.put("FLLXYZ", "GLAMOUR"); String template = "我是谁？我是$FLLXYZ不错，哈哈";
	 * merge(map, template)的结果为"我是谁？我是GLAMOUR不错，哈哈"
	 * 
	 * @param map 需要替换的键值对
	 * @param template 模板数据
	 * @return
	 */
	public static String merge(Map<String, String> map, String template) {
		if (map == null || map.isEmpty()) {
			return template;
		}
		VelocityContext context = new VelocityContext();
		for (Map.Entry<String, String> entity : map.entrySet()) {
			context.put(entity.getKey(), entity.getValue());
		}
		Writer writer = new StringWriter();
		try {
			Velocity.evaluate(context, writer, "Velocity Content Error.",
					template);
			return writer.toString();
		} catch (Exception e) {
			throw new BizException("Velocity Content Error: ", e);
		}
	}

}
